let crypto = require('crypto')
let http = require('axios')

module.exports = {
  checkSignature: function (token, sign, time, nonce) {
    let arr = [token, time, nonce]
    let str = arr.sort().join('')
    let sha1 = crypto.createHash('sha1')
    str = sha1.update(str).digest('hex')
    return sign === str
  },
  getAccessToken: function (appid, appSecret) {
    return new Promise((resolve, reject) => {
      http.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`).then(res => {
        resolve(res.data)
      })
    })
  },
  getServerList: function (accessToken) {
    return new Promise((resolve, reject) => {
      http.get(`https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=${accessToken}`).then(res => {
        resolve(res.data)
      })
    })
  },
  sendTemplateMessage: function (accessToken, msg) {
    return new Promise((resolve, reject) => {
      http.post(`https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${accessToken}`, msg).then(res => {
        resolve(res.data)
      })
    })
  }
}
